package com.pbd.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;

import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
//import com.md.bdo.ALBUMMEDIARELATION;
//import com.md.bdo.MEDIAMASTER;

public class PBDFileUpload extends Composite {

	private VerticalPanel mainPanel;
	private VerticalPanel vpLogo;
	private VerticalPanel innerPanel;
	private FormPanel uploadForm;
	private HTML pshbtnUpload;
	private Label errorLabel;
	private FileUpload fileUpload;
	private Long partyId;
	private String uploadType;
	private FlexTable showaddedFiles;

	private HorizontalPanel uploadPanel;
	private FlexTable fileUploadFlex;
	private String filePath;
	private AsyncCallback<String> asyncCallBack;
	private StringBuffer fileStorePath;
	private List mediaRelationList;

	/**
	 * @return the filePath
	 */
	public String getFilePath() {
		return filePath;
	}

	/**
	 * @param filePath
	 *            the filePath to set
	 */
	public void setFilePath(String filePath) {
		if (filePath != null && filePath.length() > 0)
			this.filePath = filePath;
	}

	public PBDFileUpload(Long partyId, String uploadType, AsyncCallback<String> asyncCallback) {
		this.partyId = partyId;
		this.asyncCallBack = asyncCallback;
		// this.title = title;
		this.uploadType = uploadType;
		// albumMediaRelationList = new ArrayList<ArrayList>();
		showaddedFiles = new FlexTable();
		showaddedFiles.setCellSpacing(3);
		innerPanel = new VerticalPanel();
		vpLogo = new VerticalPanel();
		innerPanel.setSpacing(2);
		uploadPanel = new HorizontalPanel();
		mainPanel = new VerticalPanel();
		fileUploadFlex = new FlexTable();
		uploadPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

		drawUI();
		innerPanel.setSize("350px", "100%");
		initWidget(innerPanel);

	}
	
	public PBDFileUpload(Long partyId, String uploadType) {
		this.partyId = partyId;
		// this.title = title;
		this.uploadType = uploadType;
		// albumMediaRelationList = new ArrayList<ArrayList>();
		showaddedFiles = new FlexTable();
		showaddedFiles.setCellSpacing(3);
		innerPanel = new VerticalPanel();
		vpLogo = new VerticalPanel();
		innerPanel.setSpacing(2);
		uploadPanel = new HorizontalPanel();
		mainPanel = new VerticalPanel();
		fileUploadFlex = new FlexTable();
		uploadPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

		drawUI();
		innerPanel.setSize("350px", "100%");
		initWidget(innerPanel);

	}

	public PBDFileUpload(String uploadType) {
		this.uploadType = uploadType;
		showaddedFiles = new FlexTable();
		showaddedFiles.setCellSpacing(3);
		innerPanel = new VerticalPanel();
		innerPanel.setSpacing(2);
		uploadPanel = new HorizontalPanel();
		vpLogo = new VerticalPanel();
		fileUploadFlex = new FlexTable();
		uploadPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		drawUI();
		innerPanel.setSize("350px", "100%");
		initWidget(innerPanel);

	}

	public void reset() {
		uploadForm.reset();
		// if(albumMediaRelationList!=null)
		// albumMediaRelationList.clear();
		if (showaddedFiles != null) {
			showaddedFiles.clear();
			showaddedFiles.clear(true);
		}

	}

	public void drawUI() {

		populateFileUploadWidget();
	}

	@SuppressWarnings("deprecation")
	public void populateFileUploadWidget() {

		// existAlbum = new FlexTable();
		uploadForm = new FormPanel();
		uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
		uploadForm.setMethod(FormPanel.METHOD_POST);

		fileUpload = new com.google.gwt.user.client.ui.FileUpload();

		errorLabel = new Label("");
		errorLabel.setStyleName("body_txt_black");
		errorLabel.setDirectionEstimator(true);
		errorLabel.setSize("200px", "23px");

		// if (uploadType.equalsIgnoreCase("logo")) {
		uploadForm.add(vpLogo);
		vpLogo.add(fileUploadFlex);
		vpLogo.add(errorLabel);
		vpLogo.add(showaddedFiles);
		vpLogo.setCellHorizontalAlignment(showaddedFiles, HasHorizontalAlignment.ALIGN_CENTER);

		// }
		if (partyId != null)
			mainPanel.add(errorLabel);

		fileUpload.setStyleName("btn");
		fileUpload.setName("uploadFormElement");
		fileUploadFlex.setWidget(0, 0, fileUpload);

		innerPanel.add(uploadForm);
		uploadForm.setWidth("228px");

		pshbtnUpload = new HTML("Upload");
		pshbtnUpload.setStyleName("btn");
		pshbtnUpload.setSize("70px", "20px");

		fileUploadFlex.setWidget(0, 1, pshbtnUpload);

		fileUploadFlex.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		fileUploadFlex.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_CENTER);

		pshbtnUpload.addClickHandler(new AttachFileHandler());
		uploadForm.addFormHandler(new UploadFormHandler());
	}

	class AttachFileHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {

			StringBuffer queryString = new StringBuffer("?1=1");
			if (!(uploadType.equals("logo")) || !(uploadType.equals("import"))) {
				if (partyId != null)
					queryString.append("&uploaderId=" + partyId);
			}

			if (uploadType.equals("import"))
				queryString.append("&uploadFor=import");

			System.out.println("GWT.getModuleBaseURL() :" + GWT.getModuleBaseURL() + queryString);
			errorLabel.setText("");
			uploadForm.setAction(GWT.getModuleBaseURL() + "FileUploadService" + queryString);
			uploadForm.submit();
		}
	}

	class UploadFormHandler implements FormHandler {

		@Override
		public void onSubmit(FormSubmitEvent event) {
			// ArrayList<Object> uploadedFileList = null;
			String filePath = fileUpload.getFilename();
			String fileName = null;
			String fileExtens = null;
			fileStorePath = new StringBuffer();

			if (filePath == null || !(filePath.length() > 0)) {
				errorLabel.setText("Please choose the file");
				event.setCancelled(true);
				return;
			} else {
				filePath = fileUpload.getFilename();
				System.err.println("File path" + filePath);
				fileName = filePath.split("\\\\")[2];
				fileExtens = fileName.split("\\.")[1];
			}

			// if (uploadType.equalsIgnoreCase("logo")) {
			// if (fileExtens.equalsIgnoreCase("jpg") ||
			// fileExtens.equalsIgnoreCase("png") ||
			// fileExtens.equalsIgnoreCase("jpeg") ||
			// fileExtens.equalsIgnoreCase("gif"))
			// fileStorePath.append("/UploadedFiles/Logo/" + fileName);
			// System.err.println("File Store path ::" + fileStorePath);
			// }
			//
			// else {
			System.out.println(" :::::::::::::::::: File Extension :::::::::::::::" + fileExtens);
			if (fileExtens.equalsIgnoreCase("jpg") || fileExtens.equalsIgnoreCase("png") || fileExtens.equalsIgnoreCase("jpeg") || fileExtens.equalsIgnoreCase("gif"))
				fileStorePath.append("/UploadFile/" + partyId + "/photos/" + fileName);
			else if (fileExtens.equalsIgnoreCase("mp4") || fileExtens.equals("avi") || fileExtens.equalsIgnoreCase("webm") || fileExtens.equalsIgnoreCase("3gp") || fileExtens.equalsIgnoreCase("mpeg") || fileExtens.equalsIgnoreCase("flv"))

				fileStorePath.append("/UploadFile/" + partyId + "/videos/" + fileName);

			else if (fileExtens.equals("pdf") || fileExtens.equals("doc"))
				fileStorePath.append("/UploadFile/" + partyId + "/documents/" + fileName);
			else {
				errorLabel.setText("Upload file only of types *.jpg, *.gif. *.png, *.mp4, *.3gp, *.mpeg, *.flv, *.avi, *.webm, *.pdf, *.doc ");
				return;
			}
			System.out.println("::::::::::File Path :::::::::::" + fileStorePath);

		}

		@Override
		public void onSubmitComplete(FormSubmitCompleteEvent event) {
			String responseText = event.getResults();
			responseText = responseText.substring(responseText.indexOf(">") + 1, responseText.length());
			responseText = responseText.substring(0, responseText.indexOf("<"));
			System.err.println("responseText" + responseText);

			String fileName = responseText.substring(responseText.lastIndexOf("\\") + 1, responseText.length());
			System.err.println("file name : "+fileName);
			if(fileName != null && !isFileExist(fileName)){
				HTML fileNameHtml = new HTML();
				Image deleteImage = new Image("./images/delete.gif");
				
				fileNameHtml.setText(fileName);
				fileNameHtml.setStyleName("body_txt_black");
				// fileTypeIco.setUrl("./images/picture_icon.png");
				int row = showaddedFiles.getRowCount();
				showaddedFiles.setWidget(row, 0, fileNameHtml);
				showaddedFiles.getCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
				uploadForm.reset();
				ArrayList dataValueList = new ArrayList();
				dataValueList.add(fileName);
				dataValueList.add(fileStorePath.toString());
				dataValueList.add(fileName.split("\\.")[1]);
				deleteImage.setLayoutData(dataValueList);
				showaddedFiles.setWidget(row, 1, new CheckBox());
				showaddedFiles.setWidget(row, 2, deleteImage);
				
				removeImageClickHandler(deleteImage);
				if (asyncCallBack != null)
					asyncCallBack.onSuccess(fileStorePath.toString());	
			}
		}
	}
	
	private boolean isFileExist(String fileName){
		for (int index = 0; index < showaddedFiles.getRowCount(); index++) {
			HTML html = (HTML) showaddedFiles.getWidget(index, 0);
			if (html.getText().equalsIgnoreCase(fileName)) 
				return true;
			
		}
		return false;
	}

	private void removeImageClickHandler(final Image deleteImage) {
		deleteImage.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ArrayList dataValueList = (ArrayList) deleteImage.getLayoutData();
				String fileName = (String) dataValueList.get(0);

				if (Window.confirm("Do you want to delete " + fileName + " file permanently ?")) {
					RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, "/pbd/FileUploadService");

					for (int index = 0; index < showaddedFiles.getRowCount(); index++) {
						HTML html = (HTML) showaddedFiles.getWidget(index, 0);
						if (html.getText().equalsIgnoreCase(fileName)) {
							showaddedFiles.removeRow(index);
							break;
						}
					}
					rb.setHeader("path", (String) dataValueList.get(1));
					try {
						rb.sendRequest("", new RequestCallback() {

							@Override
							public void onResponseReceived(Request request, Response response) {
								System.out.println(response.getText());

							}

							@Override
							public void onError(Request request, Throwable exception) {
								exception.printStackTrace(System.err);

							}
						});

					} catch (RequestException e) {
						e.printStackTrace();
					}
				}
			}
		});

	}

	 public List<ArrayList> getAlbumMediaRelationList() {
		 if(mediaRelationList == null)
				mediaRelationList = new ArrayList();
	
		 for (int index = 0; index < showaddedFiles.getRowCount(); index++) {
			 	CheckBox checkBox = (CheckBox) showaddedFiles.getWidget(index, 1);
				Image image = (Image) showaddedFiles.getWidget(index, 2);
				ArrayList dataValueList = (ArrayList)image.getLayoutData();
				dataValueList.add(checkBox.getValue());
				mediaRelationList.add(dataValueList);
			}
		 
		 return mediaRelationList;
				 
	 }
	 
	 public void setAlbumMediaRelation(List<ArrayList> mediaRelationList) {
		this.mediaRelationList = mediaRelationList;
		
		
		int row = showaddedFiles.getRowCount();
		
		 for (int index = 0; index < mediaRelationList.size(); index++) {
			 ArrayList dataValueList = (ArrayList)mediaRelationList.get(index);
			 HTML fileNameHtml = new HTML();
				Image deleteImage = new Image("./images/delete.gif");
				//String fileName = responseText.substring(responseText.lastIndexOf("\\") + 1, responseText.length());
				fileNameHtml.setText((String)dataValueList.get(0));
				fileNameHtml.setStyleName("body_txt_black");
				// fileTypeIco.setUrl("./images/picture_icon.png");
				showaddedFiles.setWidget(row, 0, fileNameHtml);
				showaddedFiles.getCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
				//uploadForm.reset();
				//ArrayList dataValueList = new ArrayList();
				//dataValueList.add(fileName);
				//dataValueList.add(fileStorePath.toString());
				deleteImage.setLayoutData(dataValueList);
				CheckBox checkbox = new CheckBox();
				checkbox.setValue((Boolean)dataValueList.get(3));
				showaddedFiles.setWidget(row, 1, checkbox);
				showaddedFiles.setWidget(row, 2, deleteImage);
			 
			}
		 
	 }

}
